/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Other;

import java.util.List;
import DataConnectionInterface.ConnectionPool;
import DataConnectionInterface.GameDataConnectionInterface;
import Helper.GameException;


public class UsersConcrete extends Pager implements Users {
	private List<User> usersList;

	public UsersConcrete(int entriesPerPage) {
		initUsersConcrete(entriesPerPage);
	}

	private void initUsersConcrete(int entriesPerPage) {
		super.init(entriesPerPage);
	}

	public User getUser(int index) {
		if (usersList.size() > index)
			return usersList.get(index);
		else
			return null;
	}

	public void updateUser(User user, int index) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			if (usersList.size() > index) {
				int userID = usersList.get(index).getID();
				pool = ConnectionPool.getInstance();
				con = pool.getConnection();
				con.updateUser(user, userID);
				RefreshPage(con);
				pool.returnConnection(con);
			}
		} catch (GameException e) {
			if(pool != null && con != null) pool.returnConnection(con);
		} 
	}

	public void removeUser(int index) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			if (usersList.size() > index) {
				int userID = usersList.get(index).getID();
				pool = ConnectionPool.getInstance();
				con = pool.getConnection();
				con.deleteUser(userID);
				RefreshPage(con);
				pool.returnConnection(con);
			}
		} catch (GameException e) {
			if(pool != null && con != null) pool.returnConnection(con);
		} 
	}

	// TODO: maybe not mess with the date
	public void addUser(User user) {
		ConnectionPool pool = null;
		GameDataConnectionInterface con = null;
		try {
			pool = ConnectionPool.getInstance();
			con = pool.getConnection();
			con.insertUser(user);
			RefreshPage(con);
			pool.returnConnection(con);
		} catch (GameException e) {
			if(pool != null && con != null) pool.returnConnection(con);
		}
		
	}

	public Integer getNumOfUsers() {
		return usersList.size();
	}

	public void addNewUser(String username, String pw, String descript,
			String login) {
		addUser(new UserConcrete(username, pw, descript, login, 0, 0));
	}



	// TODO: check boundaries
	protected void getNextPage(GameDataConnectionInterface con) throws GameException {
		List<User> tempList = con.getUserPage(pageNumber + 1, entriesPerPage);
		if(tempList.size() == 0) return;
		usersList = tempList;
		pageNumber++;
	}

	protected void getPreviousPage(GameDataConnectionInterface con) throws GameException {
		usersList = con.getUserPage(pageNumber - 1, entriesPerPage);
		pageNumber--;
	}

	protected void RefreshPage(GameDataConnectionInterface con) throws GameException {
		usersList = con.getUserPage(pageNumber, entriesPerPage);
	}

}
